<template>
	<div class="back_contain_n">
		<div class="leftList">
			<li v-for="(item,index) in paramList" :key="index"
				:class="{'active': viewType == item.key}"
				@click="changeView(item)"
			>
				<el-badge :value="item.num" class="item">
					<span>{{item.name}}</span>
				</el-badge>
			</li>
		</div>
		<div v-if="viewType == 'price'">
			<div class="Search_Top_Part">
				<div class="search_list">
					<div>
						<div class="input_flex">
							<el-select clearable v-model="queryForm.processName" placeholder="大类" @change="changItem">
								<el-option :label="value.name" :value="value.name" v-for="(value,key) in itemListMap"
										   :key="key"></el-option>
							</el-select>
						</div>
						<div class="input_flex">
							<el-select clearable v-model="queryForm.itemId" placeholder="品类" @change="changeCategory">
								<el-option :label="item.name" :value="item.id" v-for="(item,index) in categoryList"
										   :key="index"></el-option>
							</el-select>
						</div>
						<div class="input_flex">
							<el-select clearable v-model="queryForm.materialId" placeholder="物料代码">
								<el-option :label="item.materialCode" :value="item.id" v-for="(item,index) in materials"
										   :key="index"></el-option>
							</el-select>
						</div>
						<div class="input_flex">
							<el-select clearable v-model="queryForm.year" placeholder="年度">
								<el-option :label="item+'年'" :value="item" v-for="(item,index) in years"
										   :key="index"></el-option>
							</el-select>
							<!--<el-date-picker v-model="time"-->
							<!--type="daterange"-->
							<!--range-separator="-"-->
							<!--start-placeholder="开始日期"-->
							<!--end-placeholder="结束日期">-->
							<!--</el-date-picker>-->
						</div>
					</div>
				</div>
				<div class="search_bt">
					<span class="zll-search" @click="getList">搜索</span>
					<span class="zll-search-reset" @click="searchReset()">重置</span>
				</div>
			</div>
			<div v-if="!isSearch">
				<el-empty description="请先筛选查询条件！"></el-empty>
			</div>
			<div v-else class="_box_contain" v-show="tableData.length > 0">
				<div class="_left">
					<span class="iconfont icon-tongji"></span>
					<div>
						<p>{{queryDetail.processName}}</p>
						<p>{{queryDetail.itemName}}</p>
						<p>{{queryDetail.materialCode}},{{queryDetail.materialName}}</p>
					</div>
				</div>
				<el-row :gutter="40" class="_right">
					<el-col :span="8">
						<div class="input_flex">
							<span class="search_left">查询日期：</span>
							<span>{{queryDetail.queryTime}}</span>
						</div>
						<div class="input_flex">
							<span class="search_left">采购次数：</span>
							<span>{{queryDetail.procureCount}}</span>
						</div>
						<div class="input_flex">
							<span class="search_left">期内均价：</span>
							<span>{{queryDetail.averagePrice}}</span>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="input_flex">
							<span class="search_left">最高单价：</span>
							<div class="search_right">
								<p v-for="(price,index) in queryDetail.maxPrice" :key="index"><span style="color: #f44336">{{price.value}}</span>，{{price.time}}</p>
							</div>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="input_flex">
							<span class="search_left">最低单价：</span>
							<div class="search_right">
								<p v-for="(price,index) in queryDetail.minPrice" :key="index"><span style="color: #8bc34a">{{price.value}}</span>，{{price.time}}</p>
							</div>
						</div>
					</el-col>
				</el-row>
			</div>
			<!-- table -->
			<div style="height: 325px;" v-show="tableData.length > 0">
				<el-col v-for="(item, index) in columns" :key="index">
					<div class="box">
						<div class="content1">
							<div style="width:100px">{{ item.label }}</div>
						</div>
						<div v-for="(itC,itN) in item.value" :key="itN" class="content2">
							<div>{{ itC }}</div>
						</div>
					</div>
				</el-col>
			</div>
		</div>
	</div>
</template>

<script>
	import {formatDate} from "@/plugins/formatDate";

	export default {
		data() {
			return {
				editData: {},
				type: '',
				viewType: 'price',
				paramList: [
					{name: "原辅料价格走势", key: 'price', tableType: '1'},
					// { name: "采购任务分析",key:'采购任务分析',tableType:'2'},
					// { name: "物料明细分析",key:'物料明细分析',tableType:'2'},
				],
				tableLoading: true, //table刷新
				queryForm: {
					processName: '',
					itemId: '',
					materialId: '',
					year: '',
				},
				isSearch: false,

				tableData: [],
				columns: [
					{prop: "yearMoth", label: "年月",},
					{prop: "procureCount", label: "采购次数",},
					{prop: "total", label: "合计数量",},
					{prop: "price", label: "累计金额",},
					{prop: "averagePrice", label: "月均价",},
					{prop: "maxPrice", label: "最高单价",},
					{prop: "minPrice", label: "最低单价",},
					{prop: "distPrice", label: "波动差额",},
				],

				itemListMap: {},
				categoryList: [],
				originMaterials: [],
				materials: [],
				years: [],

				queryDetail: {
					processName: '',
					itemName: '',
					materialName: '',
					materialCode: '',
					formatMaterial: '',
					queryTime: '',
					maxPrice:[],
					minPrice:[],
					procureCount:'',
					averagePrice:'',
				},
			}
		},
		methods: {

			changItem(val) {
				this.queryForm.itemId = '';
				this.queryForm.materialId = '';
				let item = this.itemListMap[this.queryForm.processName];
				this.categoryList = item.children;
				this.materials = [];
			},

			changeCategory(val) {
				this.queryForm.materialId = '';
				let materials = this.originMaterials.filter((item) => item.categoryId == this.queryForm.itemId);
				this.materials = JSON.parse(JSON.stringify(materials))
			},

			getSysItemList() {
				let self = this;
				self.itemListMap = {};
				self.categoryList = [];
				self.materials = [];
				self.$http({
					url: "/jinl/sysItem/getMgItemSelect",
					method: "post",
					data: JSON.stringify({types: ['1']}),
					dataType: 'json',
					contentType: "application/json",
				}).then(resp => {
					if (resp.success) {
						let itemListMap = {};
						for (let data of resp.result) {
							if (itemListMap[data.itemName]) {
								itemListMap[data.itemName].children.push({id: data.id, name: data.itemAlias})
							} else {
								let obj = {name: data.itemName, children: [{id: data.id, name: data.itemAlias}]}
								itemListMap[data.itemName] = obj;
							}
						}
						self.itemListMap = itemListMap;
					}
				});
			},

			getSingleMaterialSelect() {
				let self = this;
				self.originMaterials = [];
				self.$http({
					url: "/jinl/material/getSingleMaterialSelect",
					method: "post",
				}).then(resp => {
					if (resp.success) {
						console.log(resp.result);
						self.originMaterials = resp.result;
					}
				});
			},

			getList() {
				if (!this.queryForm.materialId) {
					this.$message.warning('请选择物料');
					return;
				}
				if (!this.queryForm.year) {
					this.$message.warning('请选择查询年度');
					return;
				}
				this.isSearch = true
				this.getProcureStorageListByMaterialCode();
			},

			getProcureStorageListByMaterialCode() {
				let self = this;
				self.tableData = [];
				self.$http({
					url: "/jinl/procureStorage/getProcureStorageListByMaterialCode",
					method: "post",
					params: self.queryForm
				}).then(resp => {
					if (resp.success) {
						console.log(resp.result);
						if (resp.result.length == 0) {
							self.$message.warning('未查询到数据！');
							return;
						}
						self.tableData = resp.result;
						self.queryDetail.processName = self.queryForm.processName;
						let cate = self.categoryList.find((_data) => _data.id == self.queryForm.itemId);
						self.queryDetail.itemName = cate.itemName;
						let material = self.originMaterials.find((_data)=>_data.id == self.queryForm.materialId);
						self.queryDetail.materialName = material.materialName;
						self.queryDetail.materialCode = material.materialCode;
						self.queryDetail.queryTime = self.queryForm.year+'01-01'+'至'+self.queryForm.year+'12-31';
						let procureCount = 0;
						let index = 0;
						let averagePrice = 0.0;
						let max = [];
						let min = [];
						for(let data of self.tableData){
							if(!data.procureCount){
								continue;
							}
							procureCount +=  parseInt(data.procureCount);
							if(data.averagePrice){
								++index;
								averagePrice+=parseFloat(data.averagePrice);
							}
							if(min.length == 0){
								min.push({value:data.minPrice,time:data.yearMoth})
							}else{
								let exist = min[0].value;
								if(data.minPrice < exist){
									min = [{value:data.minPrice,time:data.yearMoth}];
								}else if(data.minPrice == exist){
									min.push({value:data.minPrice,time:data.yearMoth})
								}
							}
							if(max.length == 0){
								max.push({value:data.maxPrice,time:data.yearMoth})
							}else{
								let exist = max[0].value;
								if(data.maxPrice > exist){
									max = [{value:data.maxPrice,time:data.yearMoth}];
								}else if(data.maxPrice == exist){
									max.push({value:data.maxPrice,time:data.yearMoth})
								}
							}
						}
						self.queryDetail.procureCount = procureCount;
						self.queryDetail.maxPrice = max;
						self.queryDetail.minPrice = min;
						if(index > 0){
							averagePrice = (averagePrice/index).toFixed(1);
							self.queryDetail.averagePrice = averagePrice;
						}
						self.handleData();
					}
				});
			},

			changeView(val) {
				this.viewType = val.key;
			},
			handleData() {//获取表格数据
				this.columns.forEach(item => {
					item.value = [];
					for (let i in this.tableData) {
						for (let j in this.tableData[i]) {
							if (item.prop == j) {
								item.value.push(this.tableData[i][j]);
							}
						}
					}
				});
			},
			searchReset() { //重置搜索
				this.queryForm = {
					processName: '',
					itemId: '',
					materialId: '',
				};
				
				this.isSearch = false
				this.tableData = [];
			},

			generateCurrentTenYear() {
				let year = formatDate(new Date(), 'yyyy');
				year = parseInt(year);
				this.years = [];
				for (let i = 0; i < 10; i++) {
					this.years.push((year - i) + '');
				}
			}
		},
		created() {
			let self = this;
			self.getSysItemList();
			self.getSingleMaterialSelect();
			self.generateCurrentTenYear();
		},
		components: {},
	}
</script>

<style lang="scss" scoped>
	@import "@/style/SearchTop.scss";

	._box_contain {
		border: 1px solid #e9e9e9;
		padding: 40px;
		margin-bottom: 20px;
		display: flex;
		position: relative;

		._left {
			width: 200px;
			display: flex;
			align-items: center;

			.iconfont {
				font-size: 40px;
				color: #3F51B5;
				margin-right: 20px;
			}

			p {
				font-size: 14px;
				line-height: 30px;
			}
		}

		._right {
			width: calc(100% - 200px);

			.input_flex {
				display: flex;
				align-items: flex-start;
				line-height: 26px;

				.search_left {
					width: 72px;
					color: #9E9E9E;
					text-align: center;
				}

				.search_right {
					display: flex;
					flex-direction: column;
					line-height: 26px;
				}
			}
		}
	}

	.box {
		width: 100%;
		height: 40px;
		display: flex;
		position: relative;
		border-left: 1px solid #e9e9e9;
		border-top: 1px solid #e9e9e9;

		.content1 {
			width: 100px;
			height: 40px;
			line-height: 40px;
			text-align: center;
			color: #918d8d;
			background-color: #ddd;
			border-right: 1px solid #e9e9e9;
			border-bottom: 1px solid #e9e9e9;
			position: absolute; //表头固定
			top: 0;
		}

		.content2:nth-child(odd) { //对奇数列样式进行设置
			min-width: 80px;
			width: 8.3333%;
			height: 40px;
			line-height: 40px;
			text-align: center;
			border-right: 1px solid #e9e9e9;
			border-bottom: 1px solid #e9e9e9;
		}

		.content2:nth-child(2) {
			margin-left: 90px !important; //表头固定后，数据内容的第一列需要设置左边距空出表头的宽度
		}

		.content2:nth-child(even) { //对偶数列样式进行设置
			min-width: 80px;
			width: 8.3333%;
			height: 40px;
			line-height: 40px;
			text-align: center;
			border-right: 1px solid #e9e9e9;
			border-bottom: 1px solid #e9e9e9;
		}
	}

	.leftList {
		display: flex;
		margin-bottom: 15px;

		li {
			list-style: none;
			width: 130px;
			height: 30px;
			line-height: 28px;
			border-bottom: 1px solid #fff;
			color: #333;
			text-align: center;
			cursor: pointer;
			margin-bottom: 10px;
			transition: all .5s;
			position: relative;
			display: flex;
			justify-content: center;

			&.active {
				color: #ff9935;
				border-color: #ff9935;
				position: relative;
				font-weight: 600;
				font-size: 14px;
			}

			.nums {
				position: absolute;
				right: 5px;
				top: 0;
				background: #f44336;
				color: #fff;
				height: 16px;
				line-height: 16px;
				font-weight: 400;
				border-radius: 8px;
				font-size: 12px;
				padding: 0 5px;
			}
		}
	}
</style>